import { defineStore } from 'pinia';
import { useStorage } from '@vueuse/core';
import defAva from '@/assets/images/avatar.jpg';
import { loginService } from '@great/services';

const useUserStore = defineStore('user', () => {
    const userInfo = ref<any>();
    const token = useStorage<string | undefined>('token', undefined);
    const name = ref('');
    const nickname = ref('');
    const userId = ref<string | number>('');
    const tenantId = ref<string>('');
    const avatar = ref('');
    const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
    const permissions = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
    const menu = ref<Array<any>>();

    function setUserInfo(info: any) {
        userInfo.value = info;
        if (info) {
            const data = info;
            const user = data.user;
            const profile = user.avatar == '' || user.avatar == null ? defAva : user.avatar;

            if (data.roles && data.roles.length > 0) {
                // 验证返回的roles是否是一个非空数组
                roles.value = data.roles;
                permissions.value = data.permissions;
            } else {
                roles.value = ['ROLE_DEFAULT'];
            }
            name.value = user.userName;
            nickname.value = user.nickName;
            avatar.value = profile;
            userId.value = user.userId;
            tenantId.value = user.tenantId;
        }
    }
    function setMenu(routerMenu: any) {
        menu.value = routerMenu;
    }
    const setAvatar = (value: string) => {
        avatar.value = value;
    };
    const logout = async () => {
        await loginService.logout();
        localStorage.clear();
        sessionStorage.clear();
        window.location.href = '/login';
    };
    return {
        userInfo,
        token,
        nickname,
        userId,
        tenantId,
        avatar,
        roles,
        permissions,
        menu,
        setUserInfo,
        setMenu,
        setAvatar,
        logout
    };
});
export default useUserStore;
